//
//  NewsViewController.swift
//  Jock
//
//  Created by HD on 15/3/12.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

class NewsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, RefreshViewDelegate {
    
    private var tableView: UITableView? // UITableView
    private var refreshView: JockRefreshView?
    private var footerView: FooterView?
    private var isLoading = false
    
    private let identifier = "cell"
    private var page = 1                // 当前页数
    
    private let httpClient = HttpClient()
    
    private var news: [News] = [News]()
    private var cellImageHeight: Dictionary<Int, CGFloat> = Dictionary()

    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
        initData()
    }
    
    // 初始化界面
    private func initView() {
        tableView = UITableView(frame: CGRectMake(0, 0, view.frame.width, view.frame.height - 48))
        var inset = tableView?.contentInset
        inset?.top = 64
        tableView?.contentInset = inset!
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.registerNib(UINib(nibName:"NewsCell", bundle: nil), forCellReuseIdentifier: identifier)
        
        refreshView = ViewUtil.instanceView("JockRefreshView") as? JockRefreshView
        let refreshHeight:CGFloat = 81
        refreshView?.frame = CGRectMake(0, -refreshHeight, view.frame.width, refreshHeight)
        refreshView?.delegate = self
        refreshView?.refreshTriggerHeight = refreshHeight + 64
        tableView?.addSubview(refreshView!)
        
        footerView = ViewUtil.instanceView("FooterView") as? FooterView
        footerView?.frame = CGRectMake(0, 0, view.frame.width, 56)
        tableView?.tableFooterView = footerView
        
        self.view.addSubview(tableView!)
    }
    
    func pushToRefresh() {
        refreshView!.refreshLabel.text = "下拉刷新"
        refreshView?.refreshIndicator.hidden = true
        refreshView?.refreshIndicator.stopAnimating()
    }
    
    func releaseToRefresh() {
        refreshView!.refreshLabel.text = "释放刷新"
    }
    
    func pushOffset(offset: CGFloat) {
        
    }
    
    func refresh() {
        refreshView?.refreshIndicator.hidden = false
        refreshView?.refreshIndicator.startAnimating()
        refreshView?.refreshLabel.text = "正在刷新"
        page = 1
        loadData(true)
    }
    
    private func initData() {
        page = 1
        refreshView?.startRefresh()
    }
    
    private func loadData(refresh: Bool) {
        let url = self.url()
        isLoading = true
        HttpClient().Get(url, response: { (response) -> Void in
            if response.data != nil {
                
                self.refreshView!.endRefresh()
                let json = JSON(data: response.data!)
                if refresh {
                    self.news.removeAll(keepCapacity: false)
                }
                self.news += News.analyse(json)
                self.tableView?.reloadData()
                self.isLoading = false
            }
            }) { (error) -> Void in
                println(error)
        }
        HttpClient().Get(url, response: { (response) -> Void in
            if response.data != nil {
                
                self.refreshView!.endRefresh()
                let json = JSON(data: response.data!)
                if refresh {
                    self.news.removeAll(keepCapacity: false)
                }
                self.news += News.analyse(json)
                self.tableView?.reloadData()
                self.isLoading = false
            }
        }) { (error) -> Void in
            println(error)
        }
    }
    
    func refreshData() {
        page = 1
        loadData(true)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return news.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as? NewsCell
        cell!.news = news[indexPath.row]
        self.cellImageHeight[indexPath.row] = 220
        cell?.showData()
        return cell!
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let contentHeight = news[indexPath.row].content.stringHeightWith(16, width: self.view.frame.width)
        if news[indexPath.row].image == nil {
            return 32 + 70 + contentHeight
        }
        let imageHeight: CGFloat = CGFloat(news[indexPath.row].image_size.s.height)
        let imageWidth = CGFloat(news[indexPath.row].image_size.s.width)
        let height = imageHeight * (self.view.frame.width - 16) / imageWidth
        return 70 + height + 24 + contentHeight
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var detail = NewsDetailController()
        let news = self.news[indexPath.row]
        detail.news = news
        detail.navigationController?.navigationItem.backBarButtonItem?.title = ""
        self.navigationController?.pushViewController(detail, animated: true)
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.frame.height * 2 && !isLoading {
            page++
            loadData(false)
        }
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        tableView?.reloadData()
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            tableView?.reloadData()
        }
    }
    
    // 获取url
    private func url() -> String {
        return "http://m2.qiushibaike.com/article/list/latest?count=20&page=\(page)"
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

}
